// pages/giftSel/giftgiftSel.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: false,
    circular: false,
    current: 0,
    indicatorDots: true,
    page: 1,
    total_page: 0,
    items: [],
    total_num: 0,
    total_price: 0,
    limit: 10,
    show_type: 2, //1:酒柜 2:平台
    buyGoods: [], //购买商品列表
    detailDome: true,
    lastTime:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.goodsList();
  },

  //页面上拉触底
  onReachBottom: function(e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function() {
    var that = this;
    if (that.data.page >= that.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    that.setData({
      page: that.data.page + 1
    });
    that.goodsList();
  },

  //平台购酒商品列表
  goodsList: function() {
    var that = this;
    api.POST({
      params: {
        page: that.data.page,
        limit: that.data.limit,
      },
      url: app.globalData.base_url + 'goods/getList',
      success: function(res) {
        wx.hideLoading()
        wx.stopPullDownRefresh();
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.search;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var resultList = res.data.data.goods_list;
          resultList = that.doPingtaiData(resultList);
          if (currentPage == 1) {
            var itemData = resultList;
          } else {
            var itemData = that.data.items.concat(resultList)
          }
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            total_page: totalPage,
            items: itemData,
          });
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function(fail) {
        wx.hideLoading()
        wx.stopPullDownRefresh();
        util.showError("网络错误");
      }
    })
  },

  //处理数据
  doPingtaiData: function(list) {
    if (list.length <= 0) {
      return [];
    }
    var newList = [];
    for (var i = 0; i < list.length; i++) {
      var item = {
        id: list[i].id,
        image: list[i].image,
        product_detail_image: list[i].product_detail_image,
        list_image: list[i].list_image,
        name: list[i].gname,
        price: list[i].current_price,
        num: '',
        sku_code: list[i].sku_code,
        volume: list[i].volume,
        degree: list[i].degree,
        current_num: 0,
        isTouchMove: false,
      }
      newList.push(item)
    }
    return newList;
  },

  //增加
  addNum: function(e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    info.current_num = (info.current_num + 1);
    var items = that.data.items
    items[i] = info;
    that.setData({
      items: items
    })
    that.total_num(1)
  },

  //减少
  minusNum: function(e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (info.current_num >= 1) {
      info.current_num = (info.current_num - 1)
      var items = that.data.items;
      items[i] = info;
      that.setData({
        items: items
      })
      that.total_num(2)
    }
  },

  //总数量
  total_num: function(type = 1) {
    var that = this;
    var total_num = this.data.total_num;
    var total_price = 0;
    var buyGoods = []
    var items = that.data.items;
    for (var i = 0; i < items.length; i++) {
      if (items[i].current_num > 0) {
        var box = {};
        box.sku_code = items[i].sku_code;
        box.num = items[i].current_num;
        buyGoods.push(box);
        var num = items[i].current_num;
        var price = items[i].price / 1;
        total_price += (num * price);
      }
    }
    this.setData({
      buyGoods: buyGoods,
      total_price: total_price,
      total_num: (type == 1) ? (total_num + 1) : (total_num - 1)
    })
  },

  //支付
  submit: function(e) {

    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }


    var that = this;
    if (that.data.total_num > 0) {
        that.payOrder();
    }else{
      util.showError('请选择商品')
    }
  },

  // 支付订单
  payOrder: function() {
    var that = this;
    var buyGoods = that.data.buyGoods;
    var params = new Object()
    params.record = JSON.stringify(buyGoods)
    params.buy_type = 1;
    util.showLoading("加载中");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function(res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          wx.removeStorageSync('shopId')
          that.wxPayOrder(res.data.data.result.oid, res.data.data.result.type);
        } else {
          if (res.data.code == "2499") {
            util.showError("库存不足");
          } else {
            util.showError(res.data.message);
          }
        }
      },
      fail: function(fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //支付接口
  wxPayOrder: function(oid, types) {
    var that = this;
    api.POST({
      params: {
        oid: oid
      },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function(res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function(res) {
              wx.redirectTo({
                url: '../paySuccessful/paySuccessful?oid=' + oid
              })
            },
            fail: function(error) {
              util.showError("支付失败");
              wx.removeStorageSync('orderData');
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function(fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  // 展示详情
  showDetail: function (e) {
    console.log(e);
    var detailImg = e.currentTarget.dataset.images
    this.setData({
      detailImage: detailImg,
      detailDome: false
    })
  },

  // 隐藏详情
  close_detail: function () {
    this.setData({
      detailDome: true
    })
  },
})